<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/11/6
 * Time: 15:17
 */

namespace app\index\controller;


use app\index\service\BaseService;
use think\Config;
use think\Controller;
use think\Db;
use think\Exception;
use think\Loader;
use think\Request;

class Coupon extends Controller
{
    /**
     * @Notes:获取优惠卷类型
     * @return array
     * @author: LiBaoJin
     * @Time:
     */
    public function get_coupon_type(){
       try{
           $get_data = Db::table('ticket_type')
               ->where(['state'=>0])
               ->select();
           return ReturnData::ok($get_data,'获取优惠卷成功');
       }catch(Exception$e){
           return ReturnData::error(-1,'获取优惠卷类型失败'.$e,['']);
       }

    }

    /**
     * @Notes:添加优惠卷
     * @param Request $request
     * @return array
     * @author: LiBaoJin
     * @Time:
     */
    public function add_coupon(Request$request){
        $postData = $request->post();
        $validate = Loader::validate('Coupon');
        $rule = $validate->check($postData);
        if($rule !== true){
            return ReturnData::error(-1,$validate->getError(),['']);
        }
        if($postData['type']==1){
            if(!isset($postData['total'])||empty($postData['total'])){
                return ReturnData::error(-1,'请填写满减优惠卷的最低价格',['']);
            }
            if(!isset($postData['price'])||empty($postData['price'])){
                return ReturnData::error(-1,'请填写满减优惠卷的优惠价格',['']);
            }
        }
        if($postData['type']==2){
            if(!isset($postData['discount'])||empty($postData['discount'])){
                return ReturnData::error(-1,'请填写优惠卷折扣',['']);
            }
        }
        if($postData['type']==3){
            if(!isset($postData['money'])||empty($postData['money'])){
                return ReturnData::error(-1,'请填写优惠卷金额',['']);
            }
        }
        if(strtotime($postData['get_start_time'])>strtotime($postData['get_end_time'])){
            return ReturnData::error(-1,'优惠卷使用时间设置错误',['']);
        }
        if(strtotime($postData['get_start_time'])>strtotime($postData['expire_date'])){
            return ReturnData::error(-1,'优惠卷获取时间设置错误',['']);
        }
        $qiniuConfig = Config::get('qiniu');
        try{
            $updat = [
              'business_id'=>$this->business_id,
                'title'=>$postData['title'],
                'sub_title'=>$postData['sub_title'],
                'type'=>$postData['type'],
                'total'=>isset($postData['total'])?$postData['total']:'',
                'price'=>isset($postData['price'])?$postData['price']:'',
                'start_date'=>$postData['start_date'],
                'expire_date'=>$postData['expire_date'],
                'create_date'=>date('Y-m-d H:i:s'),
                'update_date'=>date('Y-m-d H:i:s'),
                'state'=>1,
                'remark'=>$postData['remark'],
                'picture_use'=> $qiniuConfig['domainName'].$postData['fileInfo']['picture_use'],
                'picture_used'=> $qiniuConfig['domainName'].$postData['fileInfo']['picture_used'],
                'picture_invalid'=> $qiniuConfig['domainName'].$postData['fileInfo']['picture_invalid'],
                'discount'=>isset($postData['discount'])?$postData['discount']:'',
                'money'=>isset($postData['money'])?$postData['money']:'',
                'get_start_time'=>$postData['get_start_time'],
                'get_end_time'=>$postData['get_end_time'],
                'number'=>$postData['number'],
                'can_multi_use'=>$postData['can_multi_use'],
                'can_offer'=>$postData['can_offer'],
            ];
            Db::startTrans();
            $up_id = Db::table('tickets')
                        ->insertGetId($updat);
            if(empty($up_id)){
                return ReturnData::error(-1,'添加优惠卷失败',['']);
            }
            $category_id='';
            $brand_id='';
            if(isset($postData['category_id'])){
                $category_id = $postData['category_id'];
            }
            if(isset($postData['brand_id'])){
                $brand_id = $postData['brand_id'];
            }
            Db::table('ticket_condition')
                ->insertGetId(
                    [
                        'ticket_id'     =>$up_id,
                        'category_id'   =>$category_id,
                        'brand_id'      =>$brand_id,
                        'create_time'   =>date('Y-m-d H:i:s'),
                    ]
                );
            Db::commit();
            return   ReturnData::ok($up_id,'新增优惠卷成功');
        }catch(Exception$e){
            Db::rollback();
            return ReturnData::error(-1,'添加优惠卷失败'.$e,['']);
        }


    }

    /**
     * @Notes:优惠卷展示与搜索
     * @param Request $request
     * @return array
     * @author: LiBaoJin
     * @Time:
     */
    public function  get_coupon(Request$request){
        try{
            $postData = $request->post();
            $rules = [
                'page' => 'require',
            ];
            $rule = $this->validate($postData, $rules);
            if ($rule !== true) {
                return ReturnData::error(-1, $rule);
            }
            $where = [];
            if(isset($postData['id'])&&!empty($postData['id'])){
                $where['id'] = $postData['id'];
            }
            if(!empty($postData['title'])){
                $where['title'] = ['like',"%".$postData['title']."%"];
            }
            if(!empty($postData['start_date'])&&!empty($postData['expire_date'])){
                $state = BaseService::get_state_date($postData['start_date']);
                $expire = BaseService::get_state_date(date('Y-m-d H:i:s',strtotime($postData['expire_date'].'+1 day')));
                $where['start_date'] = ['egt',$state];
                $where['expire_date'] = ['lt',$expire];
            }
            if(empty($postData['start_date'])&&!empty($postData['expire_date'])){
                $expire = BaseService::get_state_date(date('Y-m-d H:i:s',strtotime($postData['expire_date'].'+1 day')));
                $where['expire_date'] = ['lt',$expire];
            }
            if(!empty($postData['start_date'])&&empty($postData['expire_date'])){
                $state = BaseService::get_state_date($postData['start_date']);
                $where['start_date'] = ['egt',$state];
            }
            $where['business_id']=$this->business_id;
            $where['is_delete']=0;
            $ticdata=  Db::table('tickets')
                        ->where($where)
                        ->paginate(10,false,['query' => request()->param()])
                        ->toArray();
            if(empty($ticdata['data'])){
                return ReturnData::ok([''],'您还没有优惠卷');
            }
            foreach($ticdata['data'] as $k=>$v){
                $ticdata['data'][$k]['fileInfo']['picture_use']     =$v['picture_use'];
                $ticdata['data'][$k]['fileInfo']['picture_used']    =$v['picture_used'];
                $ticdata['data'][$k]['fileInfo']['picture_invalid'] =$v['picture_invalid'];
                $count = Db::table('ticket_user')
                    ->where(['ticket_id'=>$v['id']])
                    ->count();
                $ticdata['data'][$k]['count'] = $count;
                $tick_data = Db::table('ticket_condition')->where(['ticket_id'=>$v['id']])->find();
                if(isset($tick_data['category_id'])&&!empty($tick_data['category_id'])){
                    $category = Db::table('product_category')
                        ->where(['id'=>$tick_data['category_id']])
                        ->find();
                    $ticdata['data'][$k]['category_id'] = $tick_data['category_id'];
                    $ticdata['data'][$k]['category_name'] = $category['title'];
                }
                if(isset($tick_data['brand_id'])&&!empty($tick_data['brand_id'])){
                    $brand = Db::table('product_brand')
                        ->where(['id'=>$tick_data['brand_id']])
                        ->find();
                    $ticdata['data'][$k]['brand_id'] = $tick_data['brand_id'];
                    $ticdata['data'][$k]['brand_name'] = $brand['title_all'];
                }
            }
            return ReturnData::ok($ticdata,'优惠卷查询成功');
        }catch(Exception$e){
            return ReturnData::error(-1,'获取优惠卷失败'.$e);
        }

    }

    /**
     * @Notes:启动
     * @param Request $request
     * @return array
     * @throws Exception
     * @author: LiBaoJin
     * @Time:
     */
    public function up_coupon(Request$request){
        $postData = $request->post();
        $rules = [
            'id' =>'require',
            'state'=>'require'
        ];
        $rule = $this->validate($postData, $rules);
        if ($rule !== true) {
            return ReturnData::error(-1, $rule);
        }
        $get_coupon = Db::table('tickets')->where(['id'=>$postData['id'],'is_delete'=>0,'business_id'=>$this->business_id])->find();
        if(empty($get_coupon)){
            return ReturnData::error(-1, '获取优惠卷失败');
        }
        if($get_coupon['state'] !=1){
            return ReturnData::error(-1, '优惠卷不在可启用状态');
        }
        if($get_coupon['expire_date'] < date('Y-m-d H:i:s')){
            return ReturnData::error(-1, '优惠卷已过使用时间');
        }
        if($get_coupon['get_end_time'] < date('Y-m-d H:i:s')){
            return ReturnData::error(-1, '优惠卷已过领取时间');
        }
        $up = Db::table('tickets')->where(['id'=>$postData['id']])
            ->update([
                'state'=>0
                 ]);
        return ReturnData::ok([''],'启动成功');

    }

    /**
     * @Notes:优惠卷删除
     * @param Request $request
     * @return array
     * @throws Exception
     * @author: LiBaoJin
     * @Time:
     */
    public function  del_coupon(Request$request){
        $postData = $request->post();
        $rules = [
            'id' =>'require',
        ];
        $rule = $this->validate($postData, $rules);
        if ($rule !== true) {
            return ReturnData::error(-1, $rule);
        }
        $get_coupon = Db::table('tickets')->where(['id'=>$postData['id'],'is_delete'=>0,'business_id'=>$this->business_id])->find();
        if(empty($get_coupon)){
            return ReturnData::error(-1, '获取优惠卷失败');
        }
        if($get_coupon['state'] !=1){
            if($get_coupon['expire_date'] >date('Y-m-d H:i:s')){
                return ReturnData::error(-1, '优惠卷已发布且未到使用过期时间');
            }
        }
        $up = Db::table('tickets')->where(['id'=>$postData['id']])
            ->update([
                'is_delete'=>1
            ]);
        return ReturnData::ok([''],'删除成功');
    }

    /**
     * @Notes:获取s类目和品牌
     * @return array
     * @author: LiBaoJin
     * @Time:
     */
    public function get_product_category(){
        $lower_type = BaseService::get_product_category(1);
        if(empty($lower_type)){
            return ReturnData::error(-1, '获取小类目失败');
        }
        $product_brand = BaseService::get_product_brand();
        if(empty($product_brand)){
            return ReturnData::error(-1, '获取品牌失败');
        }
        return ReturnData::ok(['lower_type'=>$lower_type,'product_brand'=>$product_brand],'获取类目成功');
    }

    /**
     * @Notes:修改优惠卷
     * @param Request $request
     * @return array
     * @author: LiBaoJin
     * @Time:
     */
    public function edit_coupon(Request$request){
        $postData = $request->post();
        $validate = Loader::validate('Coupon');
        $rule = $validate->check($postData);
        if($rule !== true){
            return ReturnData::error(-1,$validate->getError(),['']);
        }
        if(!isset($postData['id'])||empty($postData['id'])){
            return ReturnData::error(-1,'请选择需要修改的优惠卷',['']);
        }
        $tickets_data = Db::table('tickets')->where(['id'=>$postData['id'],'is_delete'=>0])->find();
        if(empty($tickets_data)){
            return ReturnData::error(-1,'获取优惠券失败',['']);
        }
        if($tickets_data['state']!=1){
            return ReturnData::error(-1,'优惠卷不可以修改',['']);
        }

        if($postData['type']==1){
            if(!isset($postData['total'])||empty($postData['total'])){
                return ReturnData::error(-1,'请填写满减优惠卷的最低价格',['']);
            }
            if(!isset($postData['price'])||empty($postData['price'])){
                return ReturnData::error(-1,'请填写满减优惠卷的优惠价格',['']);
            }
        }
        if($postData['type']==2){
            if(!isset($postData['discount'])||empty($postData['discount'])){
                return ReturnData::error(-1,'请填写优惠卷折扣',['']);
            }
        }
        if($postData['type']==3){
            if(!isset($postData['money'])||empty($postData['money'])){
                return ReturnData::error(-1,'请填写优惠卷金额',['']);
            }
        }
        if(strtotime($postData['get_start_time'])>strtotime($postData['get_end_time'])){
            return ReturnData::error(-1,'优惠卷使用时间设置错误',['']);
        }
        if(strtotime($postData['get_start_time'])>strtotime($postData['expire_date'])){
            return ReturnData::error(-1,'优惠卷获取时间设置错误',['']);
        }
        $qiniuConfig = Config::get('qiniu');
        try{
            $updat = [
                'title'=>$postData['title'],
                'sub_title'=>$postData['sub_title'],
                'type'=>$postData['type'],
                'total'=>isset($postData['total'])?$postData['total']:'',
                'price'=>isset($postData['price'])?$postData['price']:'',
                'start_date'=>$postData['start_date'],
                'expire_date'=>$postData['expire_date'],
                'update_date'=>date('Y-m-d H:i:s'),
                'remark'=>$postData['remark'],
                'discount'=>isset($postData['discount'])?$postData['discount']:'',
                'money'=>isset($postData['money'])?$postData['money']:'',
                'get_start_time'=>$postData['get_start_time'],
                'get_end_time'=>$postData['get_end_time'],
                'number'=>$postData['number'],
                'can_multi_use'=>$postData['can_multi_use'],
                'can_offer'=>$postData['can_offer'],
            ];
            if(strpos($postData['fileInfo']['picture_use'],'http')!==false){
                $updat['picture_use']=$postData['fileInfo']['picture_use'];
            }else{
                $updat['picture_use']=$qiniuConfig['domainName'].$postData['fileInfo']['picture_use'];
            }
            if(strpos($postData['fileInfo']['picture_used'],'http')!==false){
                $updat['picture_used']=$postData['fileInfo']['picture_used'];
            }else{
                $updat['picture_used']=$qiniuConfig['domainName'].$postData['fileInfo']['picture_used'];
            }
            if(strpos($postData['fileInfo']['picture_invalid'],'http')!==false){
                $updat['picture_invalid']=$postData['fileInfo']['picture_invalid'];
            }else{
                $updat['picture_invalid']=$qiniuConfig['domainName'].$postData['fileInfo']['picture_invalid'];
            }
            Db::startTrans();
            Db::table('tickets')
                ->where(['id'=>$postData['id']])
                ->update($updat);
            $category_id='';
            $brand_id='';
            if(isset($postData['category_id'])){
                $category_id = $postData['category_id'];
            }
            if(isset($postData['brand_id'])){
                $brand_id = $postData['brand_id'];
            }
            Db::table('ticket_condition')
               ->where(['ticket_id'=>$postData['id']])
                ->update(
                    [
                        'category_id'   =>$category_id,
                        'brand_id'      =>$brand_id,
                        'create_time'   =>date('Y-m-d H:i:s'),
                    ]
                );
            Db::commit();
            return   ReturnData::ok([''],'修改优惠卷成功');
        }catch(Exception$e){
            Db::rollback();
            return ReturnData::error(-1,'修改优惠卷失败'.$e,['']);
        }

    }

    /**
     * @Notes:优惠卷天窗背景添加
     * @param Request $request
     * @return array
     * @author: LiBaoJin
     * @Time:
     */
    public  function add_coupon_custom(Request$request){
        $postData = $request->post();
        $rules = [
            'coupon_custom'=>'require'
        ];
        $rule = $this->validate($postData,$rules);
        if($rule !== true){
            return ReturnData::error(-1,$rule,['']);
        }
        try{
            $qiniuConfig = Config::get('qiniu');
            $popup_data = Db::table('ticket_popup')
                    ->where(['business_id'=>$this->business_id,'state'=>0])
                    ->find();
            if(empty($popup_data)){
                 Db::table('ticket_popup')
                     ->insertGetId([
                             'business_id'=>$this->business_id,
                             'picture'    =>$qiniuConfig['domainName'].$postData['coupon_custom'],
                             'create_time'=>date('Y-m-d H:i:s')
                         ]);
            }else{
                Db::table('ticket_popup')
                    ->where(['id'=>$popup_data['id']])
                    ->update([
                        'business_id'=>$this->business_id,
                        'picture'    =>$qiniuConfig['domainName'].$postData['coupon_custom'],
                        'create_time'=>date('Y-m-d H:i:s')
                    ]);
            }
            return ReturnData::ok([''],'添加成功');
        }catch(Exception$e){
            return  ReturnData::error(-1,'添加失败'.$e,['']);

        }
    }
    /**
     * @Notes:优惠卷弹窗展示
     * @return array
     * @author: LiBaoJin
     * @Time:
     */
    public function  coupon_custom_list(){
        $redata = Db::table('ticket_popup')->where(['business_id'=>$this->business_id,'state'=>0])->find();
        return ReturnData::ok([$redata,'获取列表']);
    }






























}